package org.jeecg.modules.param.area.controller;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.constant.BikeConstant;
import org.jeecg.modules.param.area.entity.BikeSysArea;
import org.jeecg.modules.param.area.entity.BikeSysUserArea;
import org.jeecg.modules.param.area.service.IBikeSysAreaService;
import org.jeecg.modules.param.area.service.IBikeSysUserAreaService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.param.member.entity.BikeMemberUserCard;
import org.jeecg.modules.param.station.entity.BikeStation;
import org.jeecg.modules.param.station.service.IBikeStationService;
import org.jeecg.modules.utils.EstUtils;
import org.jeecg.modules.utils.ExcelUtils;
import org.jeecg.modules.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 区域管理
 * @Author: 月月鸟
 * @Date:   2021-05-18
 * @Version: V1.0
 */
@Api(tags="区域管理")
@RestController
@RequestMapping("/sysarea/bikeSysArea")
@Slf4j
public class BikeSysAreaController extends JeecgController<BikeSysArea, IBikeSysAreaService>{
	@Autowired
	private IBikeSysAreaService bikeSysAreaService;
	@Autowired
	private IBikeSysUserAreaService iBikeSysUserAreaService;
	@Autowired
	private IBikeStationService bikeStationService;


	/**
	 * 分页列表查询
	 *
	 * @param bikeSysArea
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@ApiOperation(value="区域管理-分页列表查询", notes="区域管理-分页列表查询")
	@GetMapping(value = "/rootList")
	public Result<?> queryPageList(BikeSysArea bikeSysArea,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {

			String hasQuery = req.getParameter("hasQuery");
			if (hasQuery != null && "true".equals(hasQuery)) {
				QueryWrapper<BikeSysArea> queryWrapper = QueryGenerator.initQueryWrapper(bikeSysArea, req.getParameterMap());
				List<BikeSysArea> list = bikeSysAreaService.queryTreeListNoPage(queryWrapper);
				IPage<BikeSysArea> pageList = new Page<>(1, 10, list.size());
				pageList.setRecords(list);
				return Result.OK(pageList);
			} else {
				//判断父级
				String parentId = bikeSysArea.getParentId();
				if (oConvertUtils.isEmpty(parentId)) {
					parentId = "0";
				}
				bikeSysArea.setParentId(null);
				QueryWrapper<BikeSysArea> queryWrapper = QueryGenerator.initQueryWrapper(bikeSysArea, req.getParameterMap());
				// 使用 eq 防止模糊查询
				queryWrapper.eq("parent_id", parentId);
				Page<BikeSysArea> page = new Page<BikeSysArea>(pageNo, pageSize);
				IPage<BikeSysArea> pageList = bikeSysAreaService.page(page, queryWrapper);
				return Result.OK(pageList);
			}
	}

	 @ApiOperation(value = "非权限查询含网点区域树", notes = "非权限查询含网点区域树")
	 @RequestMapping(value = "/getStationTree",method = RequestMethod.POST)
	 public Result<?> getTree(BikeSysArea bikeSysArea) {
		 BikeSysUserArea bikeSysUserArea = new BikeSysUserArea();
		 return Result.OK(bikeSysAreaService.getSiteTree(bikeSysUserArea));
	 }
	 @ApiOperation(value = "权限查询含网点区域树", notes = "权限查询含网点区域树")
	 @RequestMapping(value = "/getsiteTree",method = RequestMethod.POST)
	 public Result<?> getStationTree(BikeSysArea bikeSysArea) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 BikeSysUserArea bikeSysUserArea = iBikeSysUserAreaService.selectOne(sysUser);
		 if (bikeSysUserArea!=null){
			return Result.OK(bikeSysAreaService.getSiteTree(bikeSysUserArea));
		}else {
			 //未设置权限
			 return Result.OK();
		}
	 }

	 public static void main(String[] args) {
		 String a = "a0ce11d4-a858-41ba-a2b1-047561b2c492,1cf1962b-843d-4936-8eaf-ebde2a5d7e12,14016c90-ace2-4762-a2e6-8d9a1d91ab7f";
		 String b = "f626709c-bca1-4a4e-865d-d5888ead5d4e, f907beb3-f99d-47d1-bf43-a928028e3084";
	 }
	 @ApiOperation(value = "区域管理--权限查询组织树", notes = "区域管理--权限查询组织树")
	 @RequestMapping(value = "/getOrganizationTree",method = RequestMethod.POST)
	 public Result<?> getOrganizationTree(BikeSysArea bikeSysArea) {
		 //获取权限数据
		 BikeSysArea bikeSysArea1 = new BikeSysArea();
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		 if (sysUser!=null){
			 QueryWrapper<BikeSysUserArea> wrapper = new QueryWrapper<>();
			 wrapper.eq("user_id",sysUser.getUsername());
			 List<BikeSysUserArea> list = iBikeSysUserAreaService.list(wrapper);
			 if (list.size()!=0){
				 for (BikeSysUserArea tb : list) {
					 bikeSysArea1.setId(tb.getAreaId());
				 }
				 return Result.OK(bikeSysAreaService.getOrganizationTree(bikeSysArea1, 1));
			 }
             //未设置权限
			 return Result.OK();
		 }
		 //未获取用户数据
		 return Result.OK();
	 }

	 @ApiOperation(value = "无权限展示区域树", notes = "无权限展示区域树")
	 @RequestMapping(value = "/getTreeArea",method = RequestMethod.POST)
	 public Result<?> getTreeArea(@RequestBody(required = false) BikeSysArea bikeSysArea) {
		 if (StringUtils.isNotEmpty(bikeSysArea.getName())|| StringUtils.isNotEmpty(bikeSysArea.getAreaCode())) {
			 QueryWrapper<BikeSysArea> areaQueryWrapper = new QueryWrapper<>();
			 if (StringUtils.isNotEmpty(bikeSysArea.getName())) {
				 areaQueryWrapper.like("name", bikeSysArea.getName());
			 }
			 if (StringUtils.isNotEmpty(bikeSysArea.getAreaCode())) {
				 areaQueryWrapper.like("area_code", bikeSysArea.getAreaCode());
			 }
			 List<BikeSysArea> list = bikeSysAreaService.list(areaQueryWrapper);
			 return Result.OK(list);
		 }else {
			 return Result.OK(bikeSysAreaService.getOrganizationTree(bikeSysArea,0));
		 }
	 }
	 @ApiOperation(value = "获取启用区域树", notes = "无权限展示区域树")
	 @RequestMapping(value = "/getTreeOpenArea",method = RequestMethod.POST)
	 public Result<?> getTreeOpenArea(@RequestBody(required = false) BikeSysArea bikeSysArea) {
		return Result.OK(bikeSysAreaService.getOrganizationTree(bikeSysArea,1));

	 }
	 /**
      * 获取子数据
      * @param bikeSysArea
      * @param req
      * @return
      */
	@ApiOperation(value="区域管理-获取子数据", notes="区域管理-获取子数据")
	@GetMapping(value = "/childList")
	public Result<?> queryPageList(BikeSysArea bikeSysArea,HttpServletRequest req) {
		QueryWrapper<BikeSysArea> queryWrapper = QueryGenerator.initQueryWrapper(bikeSysArea, req.getParameterMap());
		List<BikeSysArea> list = bikeSysAreaService.list(queryWrapper);
		IPage<BikeSysArea> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
		return Result.OK(pageList);
	}

    /**
      * 批量查询子节点
      * @param parentIds 父ID（多个采用半角逗号分割）
      * @return 返回 IPage
      * @param parentIds
      * @return
      */
    @ApiOperation(value="区域管理-批量获取子数据", notes="区域管理-批量获取子数据")
    @GetMapping("/getChildListBatch")
    public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<BikeSysArea> queryWrapper = new QueryWrapper<>();
			List<String> parentIdList = Arrays.asList(parentIds.split(","));
			queryWrapper.in("parent_id", parentIdList);
			List<BikeSysArea> list = bikeSysAreaService.list(queryWrapper);
			IPage<BikeSysArea> pageList = new Page<>(1, 10, list.size());
			pageList.setRecords(list);
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子节点失败：" + e.getMessage());
        }
    }
	 /**
	  *   校验添加
	  *
	  * @param bikeSysArea
	  * @return
	  */
	 @ApiOperation(value="区域管理-校验添加", notes="区域管理-校验添加")
	 @PostMapping(value = "/addCheck")
	 public Result<?> addCheck(@RequestBody BikeSysArea bikeSysArea) {
		 String YN = bikeSysAreaService.addCheck(bikeSysArea);
		 if (!YN.equals(BikeConstant.y_n_yes)){
			 return Result.error(YN);
		 }
		 return Result.OK();
	 }
	/**
	 *   添加
	 *
	 * @param bikeSysArea
	 * @return
	 */
	@AutoLog(value = "区域管理-添加")
	@ApiOperation(value="区域管理-添加", notes="区域管理-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody BikeSysArea bikeSysArea) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String id = UUID.randomUUID().toString();
		bikeSysArea.setId(id);
		String YN = bikeSysAreaService.addBikeSysArea(bikeSysArea);
		if (!YN.equals(BikeConstant.y_n_yes)){
			return Result.error(YN);
		}
		//给添加人加权限
		bikeSysAreaService.addAreaUser(sysUser,id);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param bikeSysArea
	 * @return
	 */
	@AutoLog(value = "区域管理-编辑",operateType = 3)
	@ApiOperation(value="区域管理-编辑", notes="区域管理-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody BikeSysArea bikeSysArea) {
		bikeSysAreaService.updateBikeSysArea(bikeSysArea);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "区域管理-通过id删除")
	@ApiOperation(value="区域管理-通过id删除", notes="区域管理-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {

			return bikeSysAreaService.deleteBikeSysArea(id);

	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "区域管理-批量删除")
	@ApiOperation(value="区域管理-批量删除", notes="区域管理-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.bikeSysAreaService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(value="区域管理-通过id查询", notes="区域管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		BikeSysArea bikeSysArea = bikeSysAreaService.getById(id);
		if(bikeSysArea==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(bikeSysArea);
	}

	 /**
	  * 网点区域添加校验
	  *
	  * @param id
	  * @return
	  */
	 @ApiOperation(value="区域管理-网点区域添加校验", notes="区域管理-网点区域添加校验")
	 @GetMapping(value = "/stationAddAreaCheck")
	 public Result<?> stationAddAreaCheck(@RequestParam(name="id",required=true) String id) {
		 BikeSysArea bikeSysArea = bikeSysAreaService.getById(id);
		 if(bikeSysArea!=null) {
		 	if (bikeSysArea.getHasChild().equals(BikeConstant.y_n_yes)){
		 		return Result.error("请选择最末级区域");
			}
		 }
		 return Result.OK1();
	 }
    /**
    * 导出excel
    *
    * @param request
    * @param bikeSysArea
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BikeSysArea bikeSysArea) {
		List<BikeSysArea> list = bikeSysAreaService.getExportXlsList(bikeSysArea);
		return ExcelUtils.exportXls(request,list,BikeSysArea.class,"区域管理");
    }
    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @AutoLog(value = "区域管理-导入")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return bikeSysAreaService.importExcel(request, response);
    }

}
